<template>
  <div class="page-container">
    <div class="common-content-wrap">
      <TrTable
        ref="trTable"
        v-model="searchParams"
        isNeedSelection
        :btnList="btnList"
        :searchShowList="searchShowList"
        :searchHideList="searchHideList"
        :checkSelectable="checkSelectable"
        :tableData="tableData"
        :tableColumn="tableColumn"
        :total="totalNum"
        requestName="getList"
        @rowView="viewHandle($event)"
        @rowPass="rowPassHandle($event)"
        @rowAllocate="rowAllocateHandle($event)"
        @export="exportHandle"
        @pass="passHandle"
      />
    </div>
    <TrDetail
      v-model="isShowDetailPopup"
      :leftList="detailList"
      :rightList="recordList"
      statusModel="hidden"
      :detailData="detailData"
      :width="1227"
      :isNeedFooter="isNeedFooter"
      :footerList="footerList"
      @confrim="confrimHandle"
      @pass="detailBackHandle"
      @reject="detailBackHandle"
    >
      <template #fileBlock>
        <div class="list-wrap" style="width: 100%">
          <div class="list-label">附件信息</div>
          <div class="list-value">
            <TrUploadList
              v-model="uploadList"
              action="/api/mes-quality-service/minio/common/uploadFileWithSafeName"
              fileType=".pdf,.doc,.docx,.txt,.png,.jpg,.xlsx,.xls"
              :maxFileSize="10"
            />
          </div>
        </div>
        <div class="list-wrap" style="width: 100%">
          <div class="list-label">备注说明</div>
          <div class="list-value">
            <el-input
              v-model="remarkValue"
              placeholder="请输入备注"
              type="textarea"
            ></el-input>
          </div>
        </div>
      </template>
      <template #checkDetailTable>
        <TrTable
          isPopup
          v-model="detailSearchParams"
          :tableData="detailTableData"
          :isNeedPagination="false"
          :total="detailTotal"
          :tableColumn="detailTableColumn"
          requestName="detailSearchHandle"
        />
      </template>
    </TrDetail>
    <TrForm
      v-model="isShowEdit"
      title="驳回"
      :valueObj.sync="formData"
      :list="formList"
      :width="480"
      @close="isShowEdit = false"
      @confrim="rejectHandle"
    />
    <TrForm
      v-model="isShowAllocationEdit"
      title="分配"
      :valueObj.sync="allocationFormData"
      :list="allocationFormList"
      :width="480"
      @close="isShowAllocationEdit = false"
      @confrim="comfrimAllocationHandle"
    />
  </div>
</template>

<script>
import {
  getList,
  getDetail,
  getFileList,
  updateById,
  getRecord,
  updateAudit,
  allocation,
} from "@/api/report/incoming.js";
import { getColor } from "@/utils/billColor";
import TrUploadList from "@/components/Tr-upload-list/Tr-upload-list.vue";
import TrForm from "@/components/Tr-form/Tr-form-popup.vue";
import TrTable from "@/components/Tr-table/Tr-table.vue";
import TrDetail from "@/components/Tr-detail/Tr-detail.vue";
export default {
  name: "incomingBox",
  components: {
    TrTable,
    TrDetail,
    TrUploadList,
    TrForm,
  },
  data: () => ({
    isShowAllocationEdit: false,
    allocationFormData: {},
    allocationFormList: [
      {
        id: "assignUserId",
        type: "loadselect",
        width: 100,
        label: "分配人员",
        selectedLabel: "",
        value: "",
        valueLabel: "assignUserName",
        list: [],
        requestObj: {
          url: "/api/trio-system/user/mes/page",
          method: "post",
          searchKey: "account",
          rlLabel: "username",
          rlValue: "id",
          resultKey: "data,data,records",
        },
      },
    ],
    isShowEdit: false,
    isNeedFooter: false,
    formData: {},
    formList: [
      {
        label: "驳回理由",
        type: "textarea",
        width: 100,
        value: "",
        id: "remark",
      },
    ],
    allFooterList: [
      {
        label: "取消",
        option: "close",
        color: "white",
      },
      {
        label: "驳回",
        option: "reject",
        color: "white",
      },
      {
        label: "通过",
        option: "pass",
        color: "blue",
      },
      {
        label: "保存",
        option: "confrim",
        color: "blue",
      },
    ],
    footerList: [],
    remarkValue: "",
    uploadList: [],
    detailSearchParams: {
      current: 1,
      size: 10,
      invTransId: "",
    },
    detailTotal: 0,
    detailTableColumn: [
      {
        type: "text",
        label: "检验项目",
        value: "projectName",
      },
      {
        type: "text",
        label: "数值",
        value: "standardValue",
      },
      {
        type: "text",
        label: "区间",
        value: "maxMin",
      },
      {
        type: "text",
        label: "检测数值",
        value: "testResult",
      },
      {
        type: "text",
        label: "检测结果",
        value: "testResultStateName",
      },
      {
        type: "text",
        label: "单位",
        value: "newUnitCode",
      },
    ],
    detailTableData: [],
    isShowDetailPopup: false,
    allDetailList: [
      {
        type: "text",
        id: 1,
        label: "基础信息",
        list: [
          {
            text: "报检单号",
            id: "iqcBillCode",
            width: 50,
          },
          {
            text: "采购订单号",
            id: "purcOrderCode",
            width: 50,
          },
          {
            text: "供应商名称",
            id: "supplierName",
            width: 50,
          },
          {
            text: "物料编码",
            id: "materialCode",
            width: 50,
          },
          {
            text: "物料名称",
            id: "materialName",
            width: 50,
          },
          {
            text: "物料单位",
            id: "newTestNumUnit",
            width: 50,
          },
          {
            text: "仓库",
            id: "warehouseName",
            width: 50,
          },
          {
            text: "报检数量",
            id: "testNum",
            width: 50,
          },
          {
            text: "紧急状态",
            id: "emergencyStatusName",
            width: 50,
          },
          {
            text: "报检时间",
            id: "createTime",
            width: 50,
          },
          {
            text: "报检人员",
            id: "createUserName",
            width: 50,
          },
          {
            text: "报检状态",
            id: "testStatusName",
            width: 50,
          },
        ],
      },
      {
        type: "text",
        id: 2,
        label: "质检分配",
        list: [
          {
            text: "分派时间",
            id: "assignTime",
            width: 50,
          },
          {
            text: "分派操作员",
            id: "assignUserName",
            width: 50,
          },
        ],
      },
      {
        id: 3,
        type: "slot",
        slotName: "fileBlock",
        label: "操作信息",
      },
      {
        type: "text",
        id: 4,
        label: "现场检信息",
        list: [
          {
            text: "检测结果",
            id: "testResultName",
            width: 50,
          },
          {
            text: "检测人员",
            id: "testUserName",
            width: 50,
          },
          {
            text: "检测时间",
            id: "testTime",
            width: 50,
          },
        ],
      },
      {
        id: 5,
        type: "slot",
        slotName: "checkDetailTable",
        label: "现场检明细",
        slotBottom: 32,
      },
    ],
    detailList: [],
    recordList: [
      {
        label: "审核记录",
        type: "record",
        id: "record",
        list: [],
      },
    ],
    detailData: {},
    btnList: [
      {
        label: "通过",
        option: "pass",
        color: "blue",
        isRelaTable: true,
      },
      {
        label: "导出",
        option: "export",
        color: "white",
      },
    ],
    totalNum: 0,
    tableData: [],
    searchParams: {
      current: 1,
      size: 10,
    },
    searchShowList: [
      {
        isNeed: true,
        startStr: "createTimeStart",
        endStr: "createTimeEnd",
        id: "creatTime",
        type: "daterange",
        width: 80,
        label: "创建时间",
        value: [],
        radio: 1,
        timePeriod: true,
      },
    ],
    searchHideList: [
      {
        id: "iqcBillCode",
        label: "报检单号",
        type: "input",
        value: "",
        width: 33.3,
      },
      {
        id: "testStatusList",
        label: "报检状态",
        type: "multiSelect",
        width: 33.3,
        value: [],
        list: [],
      },
      {
        id: "testResultList",
        label: "检测结果",
        type: "multiSelect",
        width: 33.3,
        value: [],
        list: [],
      },
      {
        id: "purcOrderCode",
        label: "采购订单",
        type: "loadselect",
        value: "",
        width: 33.3,
        selectedLabel: "",
        defaultParams: {},
        requestObj: {
          url: "/api/mes-warehouse-service/purc-order/page",
          method: "post",
          searchKey: "purcOrderCode",
          rlLabel: "purcOrderCode",
          rlValue: "purcOrderCode",
          resultKey: "data,data,records",
        },
      },
      {
        id: "materialCode",
        label: "物料编码",
        type: "loadselect",
        value: "",
        width: 33.3,
        selectedLabel: "",
        defaultParams: {},
        requestObj: {
          url: "/api/mes-production-service/material/page",
          method: "post",
          searchKey: "materialCode",
          rlLabel: "materialCode",
          rlValue: "materialCode",
          resultKey: "data,data,records",
        },
      },
      {
        id: "materialName",
        label: "物料名称",
        type: "loadselect",
        value: "",
        width: 33.3,
        selectedLabel: "",
        defaultParams: {},
        requestObj: {
          url: "/api/mes-production-service/material/page",
          method: "post",
          searchKey: "materialName",
          rlLabel: "materialName",
          rlValue: "materialName",
          resultKey: "data,data,records",
        },
      },
      {
        id: "supplierName",
        label: "供应商名称",
        type: "loadselect",
        value: "",
        width: 33.3,
        selectedLabel: "",
        defaultParams: {},
        requestObj: {
          url: "/api/mes-warehouse-service/supplier/page",
          method: "post",
          searchKey: "supplierName",
          rlLabel: "supplierName",
          rlValue: "supplierName",
          resultKey: "data,data,records",
        },
      },
      {
        id: "emergencyStatusList",
        label: "紧急状态",
        type: "multiSelect",
        width: 33.3,
        value: [],
        list: [],
      },
      {
        id: "testUserId",
        label: "检测人员",
        type: "loadselect",
        value: "",
        width: 33.3,
        selectedLabel: "",
        defaultParams: {},
        requestObj: {
          url: "/api/trio-system/user/mes/page",
          method: "post",
          searchKey: "username",
          rlLabel: "username",
          rlValue: "id",
          resultKey: "data,data,records",
        },
      },
      {
        startStr: "assignTimeStart",
        endStr: "assignTimeEnd",
        id: "createdTime",
        type: "daterange",
        width: 80,
        label: "分配时间",
        value: [],
        timePeriod: true,
        radio: -1,
      },
      {
        startStr: "testTimeStart",
        endStr: "testTimeEnd",
        id: "checkTime",
        type: "daterange",
        width: 80,
        label: "检测时间",
        value: [],
        timePeriod: true,
        radio: -1,
      },
    ],
    tableColumn: [
      {
        type: "text",
        label: "报检单号",
        value: "iqcBillCode",
      },
      {
        type: "text",
        label: "报检状态",
        value: "testStatusName",
      },
      {
        type: "text",
        label: "检测结果",
        value: "testResultName",
      },
      {
        type: "text",
        label: "紧急状态",
        value: "emergencyStatusName",
      },
      {
        type: "text",
        label: "采购订单号",
        value: "purcOrderCode",
      },
      {
        type: "text",
        label: "采购订单行号",
        value: "purcOrderCodeLineNo",
      },
      {
        type: "text",
        label: "物料编码",
        value: "materialCode",
      },
      {
        type: "text",
        label: "物料名称",
        value: "materialName",
      },
      {
        type: "text",
        label: "报检人员",
        value: "createUserName",
      },
      {
        type: "text",
        label: "检测人员",
        value: "testUserName",
      },
      {
        type: "text",
        label: "仓库",
        value: "warehouseName",
      },
      {
        type: "option",
        label: "操作",
        fixed: "right",
        width: 100,
        showBtnList: [
          {
            label: "查看",
            option: "rowView",
          },
          {
            label: "通过",
            option: "rowPass",
          },
          {
            label: "分配",
            option: "rowAllocate",
          },
        ],
      },
    ],
  }),
  methods: {
    async comfrimAllocationHandle() {
      let params = {
        id: this.detailData.id,
        ...this.allocationFormData,
      };
      let res = await allocation(params);
      if (res.data.code != 200) return;
      this.$message.success(this.$t("msg.success"));
      this.isShowAllocationEdit = false;
      this.$refs.trTable?.clearSelect();
      this.getList();
    },
    checkSelectable(row) {
      return row.testStatus == 40;
    },
    passHandle() {
      const selectList = this.$refs.trTable?.selectionList.map(
        (item) => item.id
      );
      this.detailBackHandle("pass", selectList);
    },
    rejectHandle() {
      this.aduitHandle(2, [this.detailData.id]);
    },
    async rowPassHandle(val) {
      this.detailBackHandle("pass", [val.id]);
    },
    rowAllocateHandle(val) {
      this.detailData = val;
      this.isShowAllocationEdit = true;
    },
    async aduitHandle(type, idList) {
      let params = {
        idList,
        auditOpt: type,
        remark: type == 2 ? this.formData.remark : "",
      };
      let { data: res } = await updateAudit(params);
      if (res.code != 200) return this.$message.error(res.msg);
      this.$message.success(this.$t("msg.success"));
      this.isShowEdit = false;
      this.isShowDetailPopup = false;
      this.$refs.trTable?.clearSelect();
      this.getList();
    },
    detailBackHandle(type, idList) {
      if (type == "reject") {
        this.isShowEdit = true;
      } else if (type == "pass") {
        this.$textShow({
          title: this.$t("tip.label"),
          content: ["是否确认审核？"],
        })
          .then(() => {
            this.aduitHandle(1, idList || [this.detailData.id]);
          })
          .catch(() => {});
      }
    },
    async confrimHandle() {
      let params = {
        fileIds: this.uploadList.map((item) => item.id),
        id: this.detailData.id,
        remark: this.remarkValue,
      };
      const { data: res } = await updateById(params);
      if (res.code != 200) return this.$message.error(res.msg);
      this.isShowDetailPopup = false;
      this.$message.success(this.$t("msg.success"));
      this.getList();
    },
    async getList() {
      const { data: res } = await getList(this.searchParams);
      if (res.code != 200) return this.$message.error(res.msg);
      this.$validateData(res.data.records);
      this.tableData = res.data.records;

      this.tableData.forEach((item) => {
        item["testStatusNameColor"] = getColor("LLBJ", item.testStatus);
        item["testResultNameColor"] = getColor("LLBJJCJG", item.testResult);
        item["isShowrowPass"] = item.testStatus !== 40;
        item["isShowrowAllocate"] = item.testStatus !== 10;
      });
      this.totalNum = res.data.total;
    },
    getShowList(state) {
      this.isNeedFooter = state != 10 && state != 20;
      if (state == 10 || state == 20) {
        this.detailList = this.allDetailList.filter((item) => item.id != 3);
        this.footerList = [];
      } else {
        this.detailList = this.allDetailList;
        if (state == 40) {
          this.footerList = this.allFooterList;
        } else {
          this.footerList = [
            this.allFooterList[0],
            this.allFooterList[this.allFooterList.length - 1],
          ];
        }
      }
    },
    async viewHandle(val) {
      this.getShowList(val.testStatus);
      const { data: res } = await getDetail(val.id);
      if (res.code != 200) return this.$message.error(res.data.msg);
      const { data: fileRes } = await getFileList(res.data.fileIds);
      const { data: record } = await getRecord(val.id);
      const recordCol = this.$findByProperty(this.recordList, "id", "record");
      recordCol.list = record.data.map((item) => {
        return {
          reTime: item.createTime,
          option: item.operTypeName,
          iconClass: item.operType == 2 ? "blue-warn" : undefined,
          labelList: [
            {
              label: "审核人员",
              value: item.createUserName,
            },
          ],
          remarkList: item.remark
            ? [
                {
                  label: "驳回理由",
                  value: item.remark,
                },
              ]
            : [],
        };
      });
      this.remarkValue = res.data.remark;
      this.uploadList = fileRes.data.map((item) => {
        return {
          ...item,
          fileName: item.originalName,
        };
      });
      this.$validateData(res.data);
      this.detailData = res.data;
      this.detailData.newTestNumUnit = `${res.data.materialUnitCode}(${res.data.materialUnitName})`;
      const statusColnum = this.$findByProperty(this.detailList, "id", 1);
      const testColnum = this.$findByProperty(
        statusColnum.list,
        "id",
        "testStatusName"
      );
      this.$set(
        testColnum,
        "valueColor",
        getColor("LLBJ", res.data.testStatus)
      );
      const reslutColnum = this.$findByProperty(this.detailList, "id", 4);
      const testResultColnum = this.$findByProperty(
        reslutColnum.list,
        "id",
        "testResultName"
      );
      this.$set(
        testResultColnum,
        "valueColor",
        getColor("LLBJJCJG", res.data.testResult)
      );
      if (res.data.testProjectResp != "-") {
        this.detailTableData = res.data.testProjectResp.testProjectDetailList;
        this.detailTableData.forEach((item) => {
          item[
            "maxMin"
          ] = `${item.standardValueMax} - ${item.standardValueMin}`;
          item["testResultStateNameColor"] = getColor(
            "LLBJJCJG",
            item.testResultState
          );
          item["newUnitCode"] = `${item.unitCode}(${item.unitName})`;
        });
      } else {
        this.detailTableData = [];
      }

      this.isShowDetailPopup = true;
    },
    exportHandle() {
      this.$exportHandle({ vm: this, params: this.searchParams });
    },
    async initHandle() {
      const res = await this.$fetchEnumApi("mes-quality-service", [
        "emergencyStatus",
        "IqcTestResult",
        "iqcTestStatus",
      ]);
      const testColnum = this.$findByProperty(
        this.searchHideList,
        "id",
        "testStatusList"
      );
      this.$set(testColnum, "list", res["iqcTestStatus"]);

      const resultColnum = this.$findByProperty(
        this.searchHideList,
        "id",
        "testResultList"
      );
      this.$set(resultColnum, "list", res["IqcTestResult"]);

      const emerColnum = this.$findByProperty(
        this.searchHideList,
        "id",
        "emergencyStatusList"
      );
      this.$set(emerColnum, "list", res["emergencyStatus"]);
    },
  },
  mounted() {
    this.initHandle();
  },
};
</script>
<style lang="scss" scoped>
.list-wrap {
  display: flex;
  align-items: flex-start !important;
  margin-bottom: 16px;
  .list-label {
    padding-top: 6px !important;
    position: relative;
    padding-right: 14px;
    text-align: right;
    font-weight: 400;
    font-size: 14px;
    color: rgba(#000, 0.4);
    word-break: break-all;
    &::after {
      position: absolute;
      content: ":";
      right: 8px;
      top: 6px !important;
      font-size: 14px;
    }
  }
  .list-value {
    // padding-right: 32px;
    flex: 1;
    color: rgba(#000, 0.9);
    word-break: break-all;
    width: 0;
    font-size: 14px;
    font-weight: 400;
  }
}
</style>
